package com.youlu.campus.service.activity.impl;

import com.alibaba.fastjson.JSON;
import com.mongodb.client.result.DeleteResult;
import com.mongodb.client.result.UpdateResult;
import com.youlu.campus.base.exception.BusinessException;
import com.youlu.campus.common.utils.Constants;
import com.youlu.campus.entity.ActivityInfo;
import com.youlu.campus.entity.ActivityPlatformConfig;
import com.youlu.campus.entity.QQConfigInfo;
import com.youlu.campus.entity.VO.req.ActivityPlatformConfigQueryVO;
import com.youlu.campus.entity.VO.res.PlatformActivityInfo;
import com.youlu.campus.entity.WechatConfigInfo;
import com.youlu.campus.entity.domain.AppDomain;
import com.youlu.campus.service.activity.ActivityPlatformConfigService;
import com.youlu.campus.service.activity.ActivityService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.data.repository.support.PageableExecutionUtils;
import org.springframework.stereotype.Service;

import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Slf4j
@Service
public class ActivityPlatformConfigServiceImpl implements ActivityPlatformConfigService {
    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private ActivityService activityService;

    @Override
    public List<ActivityPlatformConfig> find(String platform) {
        log.info(":>>> 开始获取平台配置:{}", platform);
        if (StringUtils.isBlank(platform)) {
            log.error(":>>> 平台数据为空");
            throw new BusinessException("平台数据为空");
        }
        Query query = new Query().addCriteria(Criteria.where("platform").is(platform));
        List<ActivityPlatformConfig> configs = mongoTemplate.find(query, ActivityPlatformConfig.class);
        return configs;
    }

    @Override
    public Page<ActivityPlatformConfig> list(ActivityPlatformConfigQueryVO request) {
        Query query = new Query();
        if (StringUtils.isNotBlank(request.getActivityId())) {
            query.addCriteria(Criteria.where("activityId").is(request.getActivityId()));
        }
        if (StringUtils.isNotBlank(request.getPlatform())) {
            query.addCriteria(Criteria.where("platform").is(request.getPlatform()));
        }
        if (Objects.nonNull(request.getStatus())) {
            query.addCriteria(Criteria.where("status").is(request.getStatus()));
        }
        long count = mongoTemplate.count(query, ActivityPlatformConfig.class);
        PageRequest pageRequest = PageRequest.of(request.getPage() - 1, request.getPageSize());
//        query.with(new Sort(Sort.Direction.DESC, "createdTime"));
        Sort sort=Sort.by(Sort.Direction.DESC, "createdTime");
        query.with(sort);
        List<ActivityPlatformConfig> orderPOS = mongoTemplate.find(query.with(pageRequest), ActivityPlatformConfig.class);
        if (CollectionUtils.isNotEmpty(orderPOS)) {
            for (ActivityPlatformConfig activityPlatformConfig : orderPOS) {
                if (StringUtils.isBlank(activityPlatformConfig.getActivityName())) {
                    ActivityInfo activityInfo = activityService.findOne(activityPlatformConfig.getActivityId());
                    if (Objects.nonNull(activityInfo)) {
                        activityPlatformConfig.setActivityName(activityInfo.getName());
                    }
                }
            }
        }
        return PageableExecutionUtils.getPage(orderPOS, pageRequest, () -> count);
    }

    @Override
    public boolean create(ActivityPlatformConfig req) {
        if (StringUtils.isBlank(req.getActivityId()) || Objects.isNull(req.getStatus())) {
            log.error(":>>> 创建活动平台配置错误:参数错误");
            throw new BusinessException("创建活动平台配置错误:参数错误");
        }
        ActivityInfo activityInfo = activityService.findOne(req.getActivityId());
        if (Objects.nonNull(activityInfo)) {
            req.setActivityName(activityInfo.getName());
        }
        req.setId(null);
        req.setCreatedTime(new Date());
        mongoTemplate.insert(req);
        return true;
    }

    @Override
    public boolean update(ActivityPlatformConfig req) {
        log.info(":>>> 开始修改活动平台配置:{}", JSON.toJSONString(req));
        if (Objects.isNull(req) || StringUtils.isBlank(req.getId()) || Objects.isNull(req.getStatus())) {
            log.error(":>>> 修改活动平台配置错误:参数错误");
            throw new BusinessException("修改活动平台配置错误:参数错误");
        }
        ActivityPlatformConfig config = this.findOne(req.getId());
        if (StringUtils.isNotBlank(config.getOptUserLoginName()) && !req.getOptUserLoginName().equals(config.getOptUserLoginName())) {
            log.error(":>>> 用户操作账户错误,请不要删除他人活动配置,操作人:{},创建人:{}", req.getOptUserLoginName(), config.getOptUserLoginName());
            throw new BusinessException("非法操作");
        }
        Query query = new Query().addCriteria(Criteria.where("id").is(req.getId()));
        Update update = new Update();
        if (Objects.nonNull(req.getStatus())) {
            update.set("status", req.getStatus());
        }
        if (StringUtils.isNotBlank(req.getDesc())) {
            update.set("desc", req.getDesc());
        }

        if (StringUtils.isNotBlank(req.getPlatform())) {
            update.set("platform", req.getPlatform());
        }
        if (StringUtils.isNotBlank(req.getAppId())) {
            update.set("appId", req.getAppId());
        }
        if (StringUtils.isNotBlank(req.getAppName())) {
            update.set("appName", req.getAppName());
        }
        update.set("updatedTime", new Date());
        UpdateResult updateResult = mongoTemplate.updateFirst(query, update, ActivityPlatformConfig.class);
        log.info(":>>> 修改活动平台配置结果:{},{}", req.getId(), updateResult.getModifiedCount() > 0 ? true : false);
        return updateResult.getModifiedCount() > 0 ? true : false;
    }

    @Override
    public boolean delete(String id, String optUserLoginName) {
        log.info(":>>> 开始删除活动平台配置:{}", id);
        if (!StringUtils.isNotBlank(id)) {
            log.error(":>>> 删除活动配置错误:{}", id);
            throw new BusinessException("删除活动配置错误");
        }
        ActivityPlatformConfig config = this.findOne(id);
        if (StringUtils.isNotBlank(config.getOptUserLoginName()) && !optUserLoginName.equals(config.getOptUserLoginName())) {
            log.error(":>>> 用户操作账户错误,请不要删除他人活动配置,操作人:{},创建人:{}", optUserLoginName, config.getOptUserLoginName());
            throw new BusinessException("非法操作");
        }
        Query query = new Query().addCriteria(Criteria.where("id").is(id));
        DeleteResult deleteResult = mongoTemplate.remove(query, ActivityPlatformConfig.class);
        return deleteResult.getDeletedCount() > 0 ? true : false;
    }

    @Override
    public ActivityPlatformConfig findOne(String id) {
        log.error(":>>> 开始获取活动平台配置:{}", id);
        if (!StringUtils.isNotBlank(id)) {
            log.error(":>>> 获取活动平台配置:{}", id);
            throw new BusinessException("获取活动平台配置:参数错误");
        }
        Query query = new Query().addCriteria(Criteria.where("id").is(id));
        return mongoTemplate.findOne(query, ActivityPlatformConfig.class);
    }

    @Override
    public List<AppDomain> findByPlatform(@NotNull String platform) {
        List<AppDomain> res = new ArrayList<>();
        switch (platform) {
            case "qq": {
                Query query = new Query().addCriteria(Criteria.where("platform").is(platform));
                List<QQConfigInfo> datas = mongoTemplate.find(query, QQConfigInfo.class);
                if (CollectionUtils.isNotEmpty(datas)) {
                    for (QQConfigInfo data : datas) {
                        AppDomain appDomain = new AppDomain();
                        appDomain.setAppId(data.getAppId());
                        appDomain.setAppName(data.getName());
                        res.add(appDomain);
                    }
                }
            }
            break;
            case "wechat-h5": {
                Query query = new Query().addCriteria(Criteria.where("platform").is(platform));
                List<WechatConfigInfo> datas = mongoTemplate.find(query, WechatConfigInfo.class);
                if (CollectionUtils.isNotEmpty(datas)) {
                    for (WechatConfigInfo data : datas) {
                        AppDomain appDomain = new AppDomain();
                        appDomain.setAppId(data.getAppId());
                        appDomain.setAppName(data.getName());
                        res.add(appDomain);
                    }
                }
            }
            break;
            case "wechat-mini": {
                Query query = new Query().addCriteria(Criteria.where("platform").is(platform));
                List<WechatConfigInfo> datas = mongoTemplate.find(query, WechatConfigInfo.class);
                if (CollectionUtils.isNotEmpty(datas)) {
                    for (WechatConfigInfo data : datas) {
                        AppDomain appDomain = new AppDomain();
                        appDomain.setAppId(data.getAppId());
                        appDomain.setAppName(data.getName());
                        res.add(appDomain);
                    }
                }
            }
            break;
        }
        return res;
    }

    @Override
    public List<ActivityPlatformConfig> findByAppIdAndPlatform(String appId, String platform) {
        Query query = new Query();
        query.addCriteria(Criteria.where("platform").is(platform));
        query.addCriteria(Criteria.where("appId").is(appId));
        query.addCriteria(Criteria.where("status").is(Boolean.TRUE));
        return this.mongoTemplate.find(query,ActivityPlatformConfig.class);
    }
}
